home *** CD-ROM | disk | FTP | other *** search
- Path: dimis.fage.gr!e-ID: <3168FD0A.323F@fage.gr>
- From: "E. Lefty Kreouzis" <lefty@fage.gr>
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: Mon, 08 Apr 1996 14:48:26 +0300
- Organization: FAGE S.A.
- Message-ID: <4kau8o$o46@brigitte.forthnet.gr>
- References: <31624BC2.70D2@sooner.net> <4k1vbg$6gu@newshost.cyberramp.net>
- NNTP-Posting-Host: dimis.fage.gr
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01Gold (Win95; I)
-
- John L. Noland wrote:
- >
- > n article <31624BC2.70D2@sooner.net>, edwbush@sooner.net says...
- > >
- > >I am trying to construct a C function that will recursively convert
- > >a string such as "1234" into it's integer equivelant (1234).
- > >
- > >Here is what I know:
- > >1)if you subtract the character "0" from any of the other digits "1".."9"
- > > you will get the integer value of that characer.
- > > Example: "1" - "0" is equal to 1
- > > "2" - "0" is equal to 2
- > > .
- > > .
- > > .
- > > "9" - "0" is equal to 9
- > >2)the function should be called with a character pointer:
- > > Such as: convert("1234");
- > > making the prototype look something like:
- > > int convert(char *p);
- > >
- > >Does anyone have an idea? This is sorta stumping me. I am aware of
- > >atoi, but I am wanting to write a recursive function that does that --
- > >for the fun of it. It's sort of a little puzzle to help me learn
- > >recursion. Any ideas?
- > >
- > >Thanx in Advance!
- > >
- >
- > void convert (char *buf, int result);
- >
- > int main (void) {
- >
- > char str[] = "1234";
- > int result = 0;
- >
- > convert(str, result);
- > return 0;
- >
- > }
- >
- > void convert (char *buf, int result) {
- >
- > int check_array[100]; /* Good for strings of numbers up to 100 digits long! */
- > int i = 0, j = 0;
- >
- > if (*buf = '\0') return;
- > j = i; /*Save i */
- > for (i = 0; i < 100; i++)
- > check_array[i] = 0; /*Initialize our array */
- > i = j; /*Restore i */
- > check_array[i] = (int)(*buf - '0'); /*Convert ASCII to integer and save */
- > i += 1; /*increment i */
- > j = i; /*Save i for later*/
- > for (i = 0; i < 100; i++)
- > result += check_array[i]; /*tally up the numbers */
- > i = j; /*restore i to previous */
- > buf += i; /*advance our pointer */
- > convert(buf, result);
- > if (*buf = '\0') return;
- > }
- >
- > This could probably be made a little more efficient, but I think this'll work
- > for you. Didn't test it though!
- >
- > Helping with homework is good for the soul!
- >
- > -John
-
- hmm--- what is wrong with:
-
- int convert(char *buff, int *p10)
- { int partial;
- int result;
-
- if ( !*buff )
- {
- p10 = 1;
- return 0;
- }
- partial=convert( buff+1, p10);
- result=(*buff - '0')*p10 + partial;
- *p10 *= 10;
- return result;
- }
-
- int main(void)
- {
- char snum[]="1234";
- int temp;
-
- printf("%s = %d", snum, convert(snum, temp);
- return 0;
- }
-
- Lefty.
-